<template>
  <div class="main">
    <div class="login-box">
      <div class="title">陕西华氏内容管理系统</div>
      <div class="smll-title">管理员登录</div>
      <el-form
          ref="formModelRef"
          :model="formModel"
          :rules="rules"
          class="demo-formModel"
          :size="formSize"
          status-icon
      >
        <el-form-item prop="username">
          <el-input v-model="formModel.username" placeholder="用户名"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="formModel.password"
              show-password
              placeholder="密码"
          />
        </el-form-item>
        <el-form-item>
          <div class="flex flex-between" style="width: 100%;">
            <el-checkbox v-model="rememberMe" label="记住密码">记住密码</el-checkbox>
            <span @click="showPwdDialog = true">重置密码</span>
          </div>
        </el-form-item>
        <el-form-item class="btn-group">
          <el-button type="primary" @click="submitForm(formModelRef)">
            登录
          </el-button>
          <el-button @click="resetForm(formModelRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <PwdForm :title="'重置密码'" :showDialog="showPwdDialog" @update:showDialog="(v)=>showPwdDialog = v"></PwdForm>
</template>

<script setup>
import {reactive, ref} from "vue";
import {login} from "@/api/user";
import {ElMessage} from "element-plus";
import {setToken} from "@/utils/token";
import {useRouter, useRoute} from "vue-router";
import {setUnamePwd, removeUnamePwd, getUnamePwd} from "@/utils/userinfo";
import PwdForm from "@/components/PwdForm.vue";

const formSize = ref("default");
const formModelRef = ref();
const formModel = reactive({
  username: "",
  password: "",
});

const router = useRouter();
const route = useRoute();

const rules = reactive({
  username: [
    {required: true, message: "请输入用户名", trigger: "blur"},
    {min: 3, max: 20, message: "长度范围在3--20之间", trigger: "blur"},
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        // 添加对 value 的存在性检查
        if (!value) {
          callback(new Error("请输入密码"));
        } else if (value.length < 6 || value.length > 30) {
          callback(new Error("密码长度应在6到30个字符之间"));
        } else if (
            !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/.test(
                value
            )
        ) {
          callback(
              new Error("密码必须包含大小写字母、数字和特殊字符(@$!%*?&)")
          );
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const rememberMe = ref(false);

const userPwd = getUnamePwd();
if (userPwd) {
  formModel.username = userPwd.uname;
  formModel.password = userPwd.pwd;
  rememberMe.value = true;
}
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //   console.log("submit!", formModel);
      //请求接口，登录
      login(formModel).then((res) => {
        // console.log("res:", res);
        if (res.code == 1) {
          //登录成功弹出提示 setToken
          ElMessage.success(res.msg || "登录成功");

          //   console.log("rememberMe:", rememberMe.value);
          if (rememberMe.value) {
            setUnamePwd({
              uname: formModel.username,
              pwd: formModel.password,
            });
          } else {
            removeUnamePwd();
          }

          setToken(res.data.token);
          // 跳转用户中心
          router.push(route.query.redirect || "/");
        } else {
          ElMessage.error(res.msg || "登录失败");
        }
      });

      //跳转用户中心
    } else {
      //   console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

const showPwdDialog = ref(false);
</script>

<style scoped>
.main {
  background-color: #0b4ea1;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 500px;
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* 修复这行 */
}

.title {
  text-align: center;
  font-size: 32px;
  padding: 10px 0;
  color: #0b4ea1;
}

.smll-title {
  text-align: center;
  font-size: 20px;
  padding: 15px 0;
  color: #0b4ea1;
}

.btn-group button {
  width: 244px;
}
</style>
